const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const User = require('./User');
const QuestionSet = require('./QuestionSet');

class QuestionSetExercise extends Model {}

QuestionSetExercise.init(
  {
    id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      allowNull: false,
      comment: '练习ID'
    },
    user_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '用户ID',
      references: {
        model: User,
        key: 'user_id'
      }
    },
    set_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '题库ID',
      references: {
        model: QuestionSet,
        key: 'id'
      }
    },
    status: {
      type: DataTypes.TINYINT,
      defaultValue: 0,
      comment: '状态：0-进行中，1-已完成'
    },
    question_sequence: {
      type: DataTypes.JSON,
      allowNull: false,
      comment: '题目ID序列'
    },
    current_index: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '当前题目索引'
    },
    correct_count: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      comment: '正确题目数量'
    },
    start_time: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
      comment: '开始时间'
    },
    end_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '结束时间'
    }
  },
  {
    sequelize,
    modelName: 'QuestionSetExercise',
    tableName: 'question_set_exercise',
    timestamps: false,
    indexes: [
      {
        fields: ['user_id']
      },
      {
        fields: ['set_id']
      },
      {
        fields: ['status']
      }
    ]
  }
);

// 建立与User的关联关系
QuestionSetExercise.belongsTo(User, {
  foreignKey: 'user_id',
  targetKey: 'user_id',
  as: 'user'
});

// 建立与QuestionSet的关联关系
QuestionSetExercise.belongsTo(QuestionSet, {
  foreignKey: 'set_id',
  targetKey: 'id',
  as: 'questionSet'
});

// 在User和QuestionSet模型中添加关联
setTimeout(() => {
  // 用户与题库练习的关联
  if (User.hasMany) {
    User.hasMany(QuestionSetExercise, {
      foreignKey: 'user_id',
      sourceKey: 'user_id',
      as: 'questionSetExercises'
    });
  }

  // 题库与题库练习的关联
  if (QuestionSet.hasMany) {
    QuestionSet.hasMany(QuestionSetExercise, {
      foreignKey: 'set_id',
      sourceKey: 'id',
      as: 'exercises'
    });
  }
}, 0);

module.exports = QuestionSetExercise; 